﻿using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;
using SqlSugar;

namespace SIMS.SqlSugarWebApi.Services
{
    public class RoleService : BaseService<Role>, IRoleService
    {
        private DataContext _context;

        public RoleService(DataContext context) : base(context)
        {
            _context = context;
        }

        public async Task<List<UserRights>> GetUserRights(int? userId)
        {
            if (userId != null)
            {
                var query = _context.db.Queryable<UserRole>()
                    .InnerJoin<Role>((u, r) => u.RoleId == r.Id)
                    .InnerJoin<RoleMenu>((u, r, x) => r.Id == x.RoleId)
                    .InnerJoin<Menu>((u, r, x, m) => x.MenuId == m.Id)
                    .Where(u => u.UserId == userId)
                    .Select((u, r, x, m) => new UserRights { Id = m.Id, RoleName = r.Name, MenuName = m.Name, Url = m.Url, Icon = m.Icon, ParentId = m.ParentId, SortId = m.SortId });

                return await query.ToListAsync();
            }
            return [];
        }

        public PagingModel<RoleMenu> GetRoleMenus(int? roleId)
        {
            if (roleId != null)
            {
                var roleMenus = _context.db.Queryable<RoleMenu>().Where(x => x.RoleId == roleId);
                return new PagingModel<RoleMenu>()
                {
                    Count = roleMenus.Count(),
                    Items = roleMenus.ToList()
                };
            }
            else
            {
                return null;
            }
        }

        public async Task<PagingModel<Role>> GetRoles(string roleName, int pageNum, int pageSize)
        {
            ISugarQueryable<Role> roles;
            if (!string.IsNullOrEmpty(roleName))
            {
                roles = _context.db.Queryable<Role>().Where(r => r.Name.Contains(roleName)).OrderBy(r => r.Id);
            }
            else
            {
                roles = _context.db.Queryable<Role>().OrderBy(r => r.Id);
            }
            int count = await roles.CountAsync();
            List<Role> items;
            if (pageSize > 0)
            {
                items = await roles.ToPageListAsync(pageNum, pageSize);
            }
            else
            {
                items = await roles.ToListAsync();
            }
            return new PagingModel<Role>()
            {
                Count = count,
                Items = items
            };
        }

        public async Task<int> SetRoleMenus(int roleId, string menuIds)
        {
            string[] menus = menuIds.Split(',');
            if (menus.Length == 0)
            {
                return -1;//权限为空
            }
            if (roleId < 1)
            {
                return -1;
            }

            // 删除原有角色菜单关系
            await _context.db.Deleteable<RoleMenu>().Where(r => r.RoleId == roleId).ExecuteCommandAsync();

            var entities = menus.Select(r => new RoleMenu()
            {
                RoleId = roleId,
                MenuId = int.Parse(r)
            }).ToList();

            // 批量插入新的角色菜单关系
            return await _context.db.Insertable(entities).ExecuteCommandAsync();
        }
    }
}
